package com.service.business.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.service.business.base.dto.LoginUserSession;
import com.service.business.base.service.WalletPoolService;
import com.service.business.member.controller.rep.MemberWalletRep;
import com.service.business.member.controller.req.MemberWalletPageReq;
import com.service.business.member.controller.req.MemberWalletReq;
import com.service.business.member.service.MemberService;
import com.service.core.rest.response.CommonPageRep;
import com.service.dao.enums.CoinsEnum;
import com.service.dao.enums.CommonStatusEnums;
import com.service.dao.enums.WalletEnums;
import com.service.dao.mapper.MemberWalletMapper;
import com.service.business.member.service.MemberWalletService;
import com.service.business.support.SessionUtil;
import com.service.core.exception.CommonException;
import com.service.dao.model.ConvertCoinsRecord;
import com.service.dao.model.Member;
import com.service.dao.model.MemberWallet;
import com.service.dao.model.WalletPool;
import com.service.utility.modelmapper.ModelMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年09月21日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Service
public class MemberWalletServiceImpl extends ServiceImpl<MemberWalletMapper, MemberWallet> implements MemberWalletService {
    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private WalletPoolService walletPoolService;

    @Override
    public CommonPageRep<MemberWalletRep> pageWallet(MemberWalletPageReq pageReq) {
        Page<MemberWallet> page = PageHelper.startPage(pageReq.getPageNo(), pageReq.getPageSize());

        LambdaQueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<MemberWallet>().lambda()
                .eq(MemberWallet::getMemberId, sessionUtil.getUser().getUserId())
                .eq(MemberWallet::getWalletStatus, WalletEnums.Status.ACTIVE.getCode())
                .eq(MemberWallet::getBizType, pageReq.getBizType())
                .orderByDesc(MemberWallet::getId);

        if(!ObjectUtils.isEmpty(pageReq.getCoin())){
            queryWrapper.eq(MemberWallet::getCoinsId, pageReq.getCoin().getCode());
        }
        list(queryWrapper);
        return CommonPageRep.buildResultRep(page, page.getResult().stream().map(item -> {
            MemberWalletRep result = ModelMapperUtil.getStrictModelMapper().map(item, MemberWalletRep.class);
            result.setAddressType(WalletEnums.Type.valueOf(item.getWalletType()).getName());
            return result;
        }).collect(Collectors.toList()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAddWallet(MemberWalletReq walletReq) {
        Integer memberId = sessionUtil.getUser().getUserId();
        if (!ObjectUtils.isEmpty(baseMapper.selectByName(walletReq.getWalletName(), memberId, WalletEnums.Status.ACTIVE.getCode()))) {
            throw new CommonException("该钱包备注已存在", "exist_wallet_name");
        }
        MemberWallet wallet = ModelMapperUtil.getStrictModelMapper().map(walletReq, MemberWallet.class);
        wallet.setWalletStatus(WalletEnums.Status.ACTIVE.getCode());
        wallet.setBizType(walletReq.getBType().getCode());
        wallet.setWalletType(walletReq.getType().getCode());
        wallet.setCoinsId(walletReq.getCoin().getCode());
        wallet.setCoinsName(walletReq.getCoin().getName());
        wallet.setCreateTime(new Date());
        wallet.setMemberId(memberId);
        save(wallet);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doDeleteWallet(Integer id) {
        MemberWallet wallet = new MemberWallet();
        wallet.setId(id);
        wallet.setWalletStatus(WalletEnums.Status.INVALID.getCode());
        updateById(wallet);
    }

    @Override
    public MemberWallet getOneByMemberIdAndCoin(Integer memberId, CoinsEnum coins, WalletEnums.Type type) {
        return getOne(new QueryWrapper<MemberWallet>().lambda()
                .eq(MemberWallet::getMemberId, memberId)
                .eq(MemberWallet::getCoinsId, coins.getCode())
                .eq(MemberWallet::getWalletStatus, CommonStatusEnums.ACTIVE.getCode())
                .eq(MemberWallet::getWalletType, type.getCode())
                .last("limit 1"));
    }

    @Override
    public MemberWallet getByAddress(Integer memberId, String address) {
        MemberWallet wallet = getOne(new QueryWrapper<MemberWallet>().lambda()
                .eq(MemberWallet::getMemberId, memberId)
                .eq(MemberWallet::getWalletAddr, address)
                .eq(MemberWallet::getWalletStatus, CommonStatusEnums.ACTIVE.getCode())
                .last("limit 1"));

        if (ObjectUtils.isEmpty(wallet)) {
            throw new CommonException("钱包地址不存在", "wallet_address_not_exist");
        }
        return wallet;
    }


    @Override
    public MemberWallet getByCoinIdAndBiz(Integer memberId, Integer walletStatus, Integer coin,
                                          Integer type, Integer bizType, String coins){
        MemberWallet wallet = getOne(new QueryWrapper<MemberWallet>().lambda()
                .eq(MemberWallet::getMemberId, memberId)
                .eq(MemberWallet::getWalletStatus, walletStatus)
                .eq(MemberWallet::getCoinsId, coin)
                .eq(MemberWallet::getWalletType,type)
                .eq(MemberWallet::getBizType,bizType)
                .eq(MemberWallet::getCoinsName,coins)
                .last("limit 1"));

        if (ObjectUtils.isEmpty(wallet)) {
            throw new CommonException("钱包地址不存在", "wallet_address_not_exist");
        }
        return wallet;
    }


    @Override
    public MemberWalletRep getMemberDepositAddress(CoinsEnum coin, WalletEnums.Type type) {
        LoginUserSession userSession = sessionUtil.getUser();
        return initMemberDepositAddress(userSession.getUserId(), coin, type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberWalletRep initMemberDepositAddress(Integer memberId, CoinsEnum coin, WalletEnums.Type type) {
        LambdaQueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<MemberWallet>().lambda()
                .eq(MemberWallet::getBizType, WalletEnums.BizType.recharge.getCode())
                .eq(MemberWallet::getCoinsId, coin.getCode())
                .eq(MemberWallet::getMemberId, memberId)
                .eq(MemberWallet::getWalletStatus, CommonStatusEnums.ACTIVE.getCode())
                .last("limit 1");

        if(!ObjectUtils.isEmpty(type)){
            queryWrapper.eq(MemberWallet::getWalletType, type.getCode());
        }

        MemberWallet wallet = getOne(queryWrapper);

        if (ObjectUtils.isEmpty(wallet)) {
            WalletPool walletPool = walletPoolService.getCoinsDepositAddress(coin, type);
            if (ObjectUtils.isEmpty(walletPool)) {
                return null;
            }

            wallet = new MemberWallet();
            wallet.setBizType(WalletEnums.BizType.recharge.getCode());
            wallet.setCoinsId(walletPool.getCoinsId());
            wallet.setCoinsName(walletPool.getCoinsName());
            wallet.setWalletType(walletPool.getWalletType());
            wallet.setMemberId(memberId);
            wallet.setWalletAddr(walletPool.getAddr());
            wallet.setWalletStatus(CommonStatusEnums.ACTIVE.getCode());
            wallet.setWalletName(coin.getName() + "充值");

            walletPoolService.updateById(WalletPool.builder().id(walletPool.getId())
                    .addrStatus(WalletEnums.Status.INVALID.getCode()).build());

            save(wallet);
        }

        MemberWalletRep memberWalletRep = ModelMapperUtil.map(wallet, MemberWalletRep.class);
        memberWalletRep.setAddressType(WalletEnums.Type.valueOf(wallet.getWalletType()).getName());
        return memberWalletRep;
    }
}
